<template>
	<div class="route-widthdraw">
		<van-nav-bar fixed left-text="返回" left-arrow :title="!isWeixin() ? '提现' : ''" @click-left="handleBack"
			@click-right="handleShowRuler">
			<template #right>
				<div style="color: #333;">
					交易规则
				</div>
			</template>
		</van-nav-bar>

		<div class="inner">
			<div class="card">
				<div class="title">提现到</div>
				<div>
					<van-cell :title="currentType.title" @click="showPicker = true" is-link />
				</div>
				<div class="bank" v-if="currentType.value === 3">
					<div>
						选择银行卡
					</div>
					<div class="bankcard">
						<div class="havecard" v-if="currentBank" @click="handleGoBank">
							<div class="name">
								<div class="n1">{{ currentBank.yinhang }}</div>
								<div class="n2">
									{{ maskBankCard(currentBank.bank) }}
								</div>
							</div>
							<div class="iconc">
								<van-icon name="arrow" />
							</div>
						</div>
						<div class="noneCard" v-else @click="handleGoBank">
							<van-icon name="plus" />
							<div style="padding-left: 5px;">前往添加银行卡</div>
						</div>
					</div>
				</div>
			</div>

			<div class="card">
				<div class="title">转出金额</div>
				<div class="price-cont">
					<div class="icon">￥</div>
					<van-field class="inputinfo" v-model="price" :border="false" placeholder="请输入金额" type="number" />
					<div class="text">全部</div>
				</div>
			</div>
			<div class="btn">
				<van-button type="primary" block @click="submit">提现</van-button>
			</div>
		</div>
		<van-popup v-model:show="showPicker" position="bottom">
			<van-picker :columns-field-names="{ text: 'title', value: 'value' }" :columns="columns" @confirm="onConfirm"
				@cancel="showPicker = false" />
		</van-popup>
	</div>
</template>
<script setup lang="ts">
	import { ref } from "vue";
	import { getCookie, isWeixin } from "@/utils/index";
	import { useRouter } from "vue-router";
	import { usertxApi } from '@/api/user'
	import { userbankApi } from '@/api/bank'
	import { showDialog, showToast, showLoadingToast } from 'vant';
	const router = useRouter();
	const price = ref('')
	const showPicker = ref(false);
	const userInfo = localStorage.getItem("userInfo") as any;
	const columns = ref();
	if (JSON.parse(userInfo).guanlian == 1) {
		columns.value = [{ title: '银行卡', value: 3 }]
	} else {
		columns.value = [{ title: '余额', value: 1 }, { title: '推广账户', value: 2 }, { title: '银行卡', value: 3 }]
	}


	const currentType = ref({ title: '余额', value: 1 })
	const currentBank = ref<any>('')
	const maskBankCard = (cardNumber : any) => {
		// 去除银行卡号中的非数字字符
		let numberOnly = cardNumber.replace(/\D/g, '');

		// 获取银行卡的长度
		let cardLength = numberOnly.length;

		// 根据银行卡类型在中间位置加星号
		let maskedCard = numberOnly.replace(/^(.{4})(.*)(.{4})$/, '$1 **** **** $3');

		// 对于特定的卡类型，如VISA/MASTERCARD，可以有不同的显示长度
		// 这里只是一个基础示例，根据实际需要调整

		// 返回加了空格的脱敏后的银行卡号
		return maskedCard.replace(/(.{4})/g, '$1 ').trim();
	}
	const getcard = () => {
		userbankApi({ uid: getCookie('token') ? Number(getCookie('token')) : '', }).then((res) => {
			let data = res.data
			if (localStorage.getItem('bank') === '{}') {
				localStorage.removeItem('bank')
			}
			if (data.length) {
				if (localStorage.getItem('bank')) {
					currentType.value = { title: '银行卡', value: 3 }
					console.log(currentType.value)
					currentBank.value = JSON.parse(localStorage.getItem('bank') as any)
				} else {
					currentBank.value = data[0]
				}
			} else {
				localStorage.removeItem('bank')
				currentBank.value = ''
			}
		})
	}
	getcard()
	const initData = () => {

	}
	const handleGoBank = () => {
		router.push({
			path: '/banklist',
			query: { from: 'tixian' }
		})
	}
	const handleBack = () => {
		if (history.state?.back) {
			router.back()
		} else {
			router.push('/user')
		}
	};
	const handleShowRuler = () => {
		showDialog({
			title: '交易规则',
			message: '交易规则',
		}).then(() => {
			// on close
		});
	}
	const onConfirm = ({ selectedOptions } : any) => {

		currentType.value = selectedOptions[0]
		showPicker.value = false
		if (currentType.value.value === 3) {
			localStorage.setItem('bank', JSON.stringify(currentBank.value || {}))
		} else {
			localStorage.removeItem('bank')
		}
	}

	const submit = async () => {
		if (!price.value) {
			showToast({
				message: "请输入金额",
				position: "top",
			});

			return;
		}
		if (currentType.value.value === 3 && !currentBank.value) {
			showToast({
				message: "请选择银行卡",
				position: "top",
			});
			return;
		}
		let bankid = currentBank.value?.id || ''
		let toast = showLoadingToast({
			duration: 0,
			message: '申请中...',
			forbidClick: true,
		});
		let { code, msg } = await usertxApi({
			uid: getCookie('token') ? Number(getCookie('token')) : '',
			price: Number(price.value),
			status: currentType.value.value,
			bankid
		})
		toast.close()
		if (code === 0) {
			price.value = ''
			showDialog({
				title: '提示',
				message: '体现申请成功！',
			}).then(() => {
				// on close
				localStorage.removeItem('bank')
				router.back()
			});

		} else {
			showToast({
				message: msg,
				position: "top",
			});
		}
	}
</script>
<style lang="scss" scoped>
	@import './index.scss'
</style>